package com.auto.learning.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.adapter.VideoPageAdapter;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.bean.VideoBean;
import com.auto.learning.event.Handle;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.sharesdk.tools.ShareOpUtils;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.auto.learning.view.ShareView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class VideoPageFragment extends Fragment implements Callback {
	
	private final static int GETCACHEDATA = 1;
	public final static int SHARE = 2;
	private PullToRefreshListView listview_video;
	private VideoPageAdapter adapter;
	private ArrayList<VideoBean> list = new ArrayList<VideoBean>();
	private int pageIndex = 0;
	
	private View lvProductFooter;
	private TextView lvProductFooterMore;
	private ProgressBar lvProductFooterProgress;
	private TextView lvBtn_more;
	private LinearLayout lvLinear_more;
	private RelativeLayout relative_main;
	
	Handle handle = new Handle(getActivity()){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				String bottom = "";
				ResponeResult result =(ResponeResult) msg.obj;
				ArrayList<VideoBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<VideoBean>>() {}.getType());
				if (pageIndex == 0) {
					list.clear();
					list.addAll(resultList);
					Cache.cacheVideo2Local(resultList);
				} else {
					list.addAll(resultList);
				}
				if (resultList.size() >= 10) {
					pageIndex ++;
					lvBtn_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
				}else {
					bottom = getResources().getString(R.string.text_video_data);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
					lvProductFooterProgress.setVisibility(View.GONE);
					lvBtn_more.setVisibility(View.GONE);
				}
				
				if (listview_video != null) {
					listview_video.onRefreshComplete();
					listview_video.setTag(0);
				}
				if (list != null && list.size() > 0) {
					adapter.notifyDataSetChanged();
				}
				break;
			case HttpRequestHelper.GETDATA_FAIL:
				CommonMethod.makeNotice(getActivity(), msg.obj.toString());
				if (listview_video != null) {
					listview_video.onRefreshComplete();
					listview_video.setTag(0);
				}
				break;
			case GETCACHEDATA:
				ArrayList<VideoBean> temp_list =(ArrayList<VideoBean>) msg.obj;
				if (temp_list != null && temp_list.size() > 0) {
					list.clear();
					list.addAll(temp_list);
					if (adapter != null) {
						adapter.notifyDataSetChanged();
					}
				}
				getData();
				break;
			case SHARE:
				VideoBean mVideoBean = (VideoBean) msg.obj;
				if (mVideoBean != null) {
					String url = HttpCommonInfo.MURL +"video-detail?id=" + mVideoBean.getId();
					String title = mVideoBean.getTitle();
					new ShareView(getActivity(), VideoPageFragment.this).setTitle(title).setUrl(url).setContent(mVideoBean.getSlogan()).setImageUrl(mVideoBean.getVideoImg()).setId(mVideoBean.getId()+"").setType(2).show(relative_main);
				}
				break;
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.videopage_fragment, null);
		initView(view);
		getCacheData();
		return view;
	}
	
	private void getCacheData(){
		Cache.getVideoCache(handle, GETCACHEDATA);
	}
	
	private void initView(View view){
		lvProductFooter = getActivity().getLayoutInflater().inflate(R.layout.listview_footer, null);
		lvProductFooterMore = (TextView) lvProductFooter.findViewById(R.id.listview_foot_more);
		lvProductFooterProgress = (ProgressBar) lvProductFooter.findViewById(R.id.listview_foot_progress);
		lvBtn_more = (TextView) lvProductFooter.findViewById(R.id.btn_more);
		lvBtn_more.setTextColor(getResources().getColor(R.color.main_green_color));
		lvProductFooterMore.setTextColor(getResources().getColor(R.color.main_green_color));
		lvLinear_more = (LinearLayout) lvProductFooter.findViewById(R.id.linear_more);
		relative_main = (RelativeLayout) view.findViewById(R.id.relative_main);
		listview_video = (PullToRefreshListView) view.findViewById(R.id.listview_video);
		listview_video.setTag(0);
		adapter = new VideoPageAdapter(getActivity(),list, handle);
		listview_video.setAdapter(adapter);
		/*listview_video.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position - 1 < list.size()) {
					Intent intent = new Intent(getActivity(),VideoPlayActivity.class);
					intent.putExtra("m_bean", list.get(position - 1));
					startActivity(intent);
				}
			}
		});*/
		
		
		listview_video.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				pageIndex = 0;
				getData();
			}
		});
		
		listview_video.addFooterView(lvProductFooter);
		lvBtn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getData();
			}
		});
		listview_video.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				listview_video.onScrollStateChanged(view, scrollState);
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvProductFooter) == view.getLastVisiblePosition()
							&& !lvProductFooterMore.getText().toString().equals( getResources().getString(R.string.text_video_data))) {
						scrollEnd = true;
					}
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				int lvDataState = Integer.parseInt((listview_video.getTag().toString()));
				if (scrollEnd && lvDataState == 0) {
					listview_video.setTag(1);
					lvProductFooterMore.setText("加载中");
					lvProductFooterProgress.setVisibility(View.VISIBLE);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvBtn_more.setVisibility(View.GONE);
					getData();
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				listview_video.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		
	}
	
	private void getData(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(getActivity(), HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String.valueOf(pageIndex)));
		HttpRequestHelper.executeHttpData(getActivity(), HttpRequestHelper.HALL_OF_FAME, params, handle, HttpRequestHelper.GETDATA_SUCCESS,HttpRequestHelper.GETDATA_FAIL);
	}

	@Override
	public boolean handleMessage(Message msg) {
		ShareOpUtils.handleShareCallBack(getActivity(), msg);
		return false;
	}
	
}
